
//
//  BKMain_WebViewController.m
//  bestkeep
//
//  Created by yons on 16/12/13.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKMain_WebViewController.h"
#import <NJKWebViewProgressView.h>
#import <NJKWebViewProgress.h>
#import <Masonry.h>
#import <MJExtension.h>
#import "Mediator+BKGD.h"
#import "Mediator+BKClassify.h"
#import "Mediator+BKMy.h"
#import "BKMainCommon.h"
@interface BKMain_WebViewController ()<UIWebViewDelegate,NJKWebViewProgressDelegate>

@property(nonatomic,strong)NJKWebViewProgressView *progressView;
@property(nonatomic,strong)NJKWebViewProgress *progress;
@property(nonatomic,strong)UIWebView *webView;
@property(nonatomic,strong)NSString *backString;
@property(nonatomic,assign)BOOL isFirst;
@property(nonatomic,strong)ExceptionView *exceptionView;

@end

@implementation BKMain_WebViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    self.view.backgroundColor=[UIColor whiteColor];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
//    self.navigationController.navigationBar.clipsToBounds = NO;
    self.title = self.webViewTitle;
    if ([self.type_Share isEqualToString:@"1"] && ![self.shareTitle isEqualToString:@""]&& ![self.shareContent isEqualToString:@""]&&![self.shareImg isEqualToString:@""]) {
        UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"BKMain_share"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(shareAction)];
        [rightBarBtn setImageInsets:UIEdgeInsetsMake(0, -8, 0, 8)];
        self.navigationItem.rightBarButtonItem = rightBarBtn;
    }
    
    if ([BKMainCommon checkNetWork] == YES) {
        [self loadWebView];
    }
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _progressView.hidden=YES;
    
}
-(void)shareAction{
    __weak typeof(self) weakSelf = self;
    ShareManager *shareManager = [ShareManager manager];
    
    [shareManager showShareMenuInController:self sharePlatformSelectionBlock:^ShareObject *(SharePlatformType type) {
        ShareObject *obj = [[ShareObject alloc]init];
        obj.title = weakSelf.title;
        NSString *shareurl = [NSString stringWithFormat:@"%@?isH5=true",weakSelf.webViewUrl];
        obj.webpageUrl = shareurl;
        obj.descr = weakSelf.shareContent;
        obj.thumbImage = weakSelf.shareImg;
        return obj;

    } callBack:^(id response, NSError *error) {
        NSLog(@"%@",response); 
        if (error) {
            [HUD showErrorMessage:@"分享取消"];
        }else if ([response isEqual:NULL]){
            [HUD showErrorMessage:@"分享失败"];
            NSLog(@"----------分享失败----------");
        }else{
            NSLog(@"------------分享成功----------------");
            [HUD showSuccessMessage:@"分享成功"];
            if ([BKMainCommon islogin]) {
                //判断是否有code值，送券
                if ([self.shareFlag isEqualToString:@"1"]) {
                    if (![self.shareCode isEqualToString:@""]){
                        RequestManager *manger = [RequestManager manager];
                        NSDictionary *parametersDic =[NSDictionary dictionaryWithObjectsAndKeys:self.shareCode,@"code", nil];
                        [manger bkDataRequest:RequestMethodPost URLString: [BKMainCommon ServicesURL:@"/shopping-tick/shareBannerPromotion"] parameters:parametersDic success:^(id  _Nullable responseObject) {
                            NSLog(@"----送券结果--%@",responseObject);
                            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                                if ([[responseObject allKeys] containsObject:@"success"]) {
                                    
                                    
                                }
                            }
                            
                        } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
                            
                            
                        }];

                }
                
                }

            }
            
            
        }
    }];
}
-(void)loadWebView{
    

    
    _progress = [[NJKWebViewProgress alloc]init];
    _progress.webViewProxyDelegate = self;
    _progress.progressDelegate = self;
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectZero];
    _webView.backgroundColor = [UIColor clearColor];
    _webView.scrollView.bounces = NO;
    [self.view addSubview:_webView];
    _webView.delegate = _progress;
    _webView.scrollView.directionalLockEnabled = NO;
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.height.mas_equalTo(@(CGRectGetHeight([UIScreen mainScreen].bounds)-64));
        make.right.equalTo(self.view. mas_right).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(0);
    }];
    
    CGRect navBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0,
                                 navBounds.size.height - 2,
                                 navBounds.size.width,
                                 2);
    _progressView = [[NJKWebViewProgressView alloc]initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [_progressView setProgress:0 animated:YES];
    [self.navigationController.navigationBar addSubview:_progressView];

    if ([[NSString stringWithFormat:@"%@", self.type] isEqualToString:@"4"]) {
        
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_webViewUrl] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60]];
    }else{
        NSString *st = [[Mediator sharedInstance]BKMyUserInfo][BKMyUserGetUTOUUPlatformSTkey];
        NSString *urlStr = [NSString stringWithFormat:@"%@?ticket=%@",_webViewUrl,st];
        NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        [self.webView loadRequest:request];
        for (UIView *_aView in [self.webView subviews])
        {
            if ([_aView isKindOfClass:[UIScrollView class]])
            {
                [(UIScrollView *)_aView setShowsVerticalScrollIndicator:NO];
                //右侧的滚动条
            }
        }
        self.webView.scrollView.bounces = NO;
    }

}
- (void)didFinishLoadHtml{
    
    
    if (self.oneUrl == nil || [self.oneUrl isEqualToString:@""]) {
        
        [_webView stringByEvaluatingJavaScriptFromString: @"OBJC.executeJs(\"init\",\"{}\")"];
    }
}
#pragma mark - --------------NJKWebViewProgressDelegate------------------
- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress{
    [_progressView setProgress:progress animated:YES];
    if (!self.title) {
        self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    }
}
#pragma mark   --------------UIWebViewDelegate-----------------------------
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *requestString = [[request URL]absoluteString];
    requestString = [requestString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *url = [NSString stringWithFormat:@"%@", request.URL];
    
    NSString *header = @"http://objc/";
    if ([url hasPrefix:header]) {
        
        BOOL shops = NO;
        NSArray *components = [requestString componentsSeparatedByString:@"http://objc/"];
        if (components.count > 1) {
            NSUInteger range = [requestString rangeOfString:@"{"].location;
            NSString *b = [requestString substringFromIndex:range];
            
            NSDictionary *param_dic = (NSDictionary *)[b mj_JSONObject];
//            NSLog(@"%@",param_dic);
            NSArray *widget = [param_dic objectForKey:@"widget"];
            if ([widget containsObject:@"shopcarbtn"] ) {
                shops = YES;
                
            }else if ([[param_dic objectForKey:@"action"] isEqualToString:@"open"]){
                NSString * number = [param_dic objectForKey:@"target"];
                if ([number isEqualToString:@"info"]) {
                    NSDictionary *dic = [param_dic objectForKey:@"parameters"];
                    Mediator *mediator = [Mediator sharedInstance];
                     animated:YES;
                    if ([dic[@"type"] isEqualToString:@"1"]) {
    
                        UIViewController *detailVC = [mediator BKGD_goodsDetailViewController:dic[@"goodsNo"]saleTypes:@""];
                        detailVC.view.backgroundColor = [UIColor whiteColor];
                        [self.navigationController pushViewController:detailVC animated:YES];
                        
                    }else if([dic[@"type"] isEqualToString:@"2"]){
                        
                        Mediator *mediator = [Mediator sharedInstance];
                        UIViewController *classifyVC = [mediator HomeIntorecordPushInformationWithFilterTerms:@"-1" categotyId:@"" channelType:dic[@"code"] orderKey:@"" currentPage:0 keyWord:@"" order:@""];
                        [self.navigationController pushViewController:classifyVC animated:YES];

                    }
                    
                    
                }else if([number hasPrefix:@"http"]){
                    
                    
                }
            }else if ([[param_dic objectForKey:@"action"] isEqualToString:@"close"]){
                
                UIWebView *web = (id)[self.view viewWithTag:99];
                [web removeFromSuperview];
                NSURL *url =[NSURL URLWithString:_webViewUrl];
                NSURLRequest *request =[NSURLRequest requestWithURL:url];
                [self.webView loadRequest:request];
            }
        }
    }
    
    return YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {//html加载完后触发
    NSLog(@"结束加载时调用的方法:--%@", [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"] );
    [self didFinishLoadHtml];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    if ([_backString rangeOfString:@"{"].location != NSNotFound) {
        NSUInteger range = [_backString rangeOfString:@"{"].location;
        NSString *b = [_backString substringFromIndex:range];
        NSDictionary *param_dic = (NSDictionary *)[b mj_JSONObject];
        if ([[param_dic objectForKey:@"action"] isEqualToString:@"close"]){
            NSURL *url =[NSURL URLWithString:_webViewUrl];
            NSURLRequest *request =[NSURLRequest requestWithURL:url];
            [self.webView loadRequest:request];
        }
    }else{
        
        [self didFailLoadHtml:error];
    }
}
-(void)didFailLoadHtml:(NSError *)error{
    
    
    if (error) {
        [_exceptionView removeFromSuperview];
         __weak typeof(self)wself = self;
        _exceptionView = [ExceptionView  exceptionViewWithType:ExceptionCodeTypeFailedToLoad];
        ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:ExceptionCodeTypeFailedToLoad handler:^(ExceptionViewAction *action) {
            NSURL *url =[[NSURL alloc]initWithString:wself.webViewUrl];
            NSURLRequest *request =[[NSURLRequest alloc]initWithURL:url];
            
            [wself.webView loadRequest:request];
        }];
        [self.exceptionView addAction:retryAction];
        [self.exceptionView showInView:self.view];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
